package cn.gjxblog.modules.job.service.impl;

import cn.gjxblog.common.model.PageInfo;
import cn.gjxblog.common.model.PageRequest;
import cn.gjxblog.modules.job.dao.ScheduleJobDao;
import cn.gjxblog.modules.job.entity.ScheduleJobEntity;
import cn.gjxblog.modules.job.service.ScheduleJobService;
import cn.gjxblog.modules.job.utils.ScheduleUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 定时任务服务实现类
 *
 * @author guojiaxun
 * @date 2019-09-18 13:53:04
 */
@Service("scheduleJobService")
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
    @Autowired
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     * @param
     * @return
     */
    @PostConstruct
    public void init(){
        List<ScheduleJobEntity> list = this.list();
        for (ScheduleJobEntity scheduleJob : list) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            }else{}

        }
    }

    @Override
    public PageInfo searchList(PageRequest request) {
        QueryWrapper<ScheduleJobEntity> ew = new QueryWrapper<>();

        IPage<ScheduleJobEntity> page = this.page(new Page<>(request.getPageNum(), request.getPageSize()),ew);
        return new PageInfo(page);
    }

    @Override
    public void run(Long[] jobIds) {
        for(Long jobId : jobIds){
            ScheduleUtils.run(scheduler, this.getById(jobId));
        }
    }

}